package servlets;

import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;


@SuppressWarnings("serial")
public class FileUploadHandler extends HttpServlet {
	private String UPLOAD_DIRECTORY = "";

	@SuppressWarnings("unchecked")
	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		//TODO SERVLET
		
		String raAluno = "";
		String nomeAluno = "";
		
		UPLOAD_DIRECTORY = getServletContext().getRealPath("\\")+"Provas"; 
		File dir = new File(UPLOAD_DIRECTORY);
		if (!dir.exists()) {
			dir.mkdir();
		}

		if (ServletFileUpload.isMultipartContent(request)) {
			String name = "";
			try {
				List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

				for (FileItem item : multiparts) {
					if (!item.isFormField()) {
						name = new File(item.getName()).getName();
						this.validacao(name);
						File arq = new File(UPLOAD_DIRECTORY, name);

						if (arq.exists()){
							arq.delete();
						}
						
						item.write(new File(UPLOAD_DIRECTORY + File.separator + name));
					} else {
						String fieldname = item.getFieldName();
						if (fieldname.equals("ra")){
							raAluno = item.getString();
						}
						if (fieldname.equals("nome")){
							nomeAluno = item.getString();
						}
					}
				}
				
				// File uploaded successfully
				File renome = new File(UPLOAD_DIRECTORY + File.separator + name);
				String extensao = renome.getName().substring(renome.getName().lastIndexOf("."),renome.getName().length());
				renome.renameTo(new File(UPLOAD_DIRECTORY + File.separator + raAluno + "_" + nomeAluno + extensao));
				request.setAttribute("message", "Arquivo carregado com sucesso!");
			} catch (Exception ex) {
				request.setAttribute("message", "Erro ao carregar " + name + " devido a " + ex);
			}

		} else {
			request.setAttribute("message", "Sorry this Servlet only handles file upload request");
		}

		request.getRequestDispatcher("/index.jsp").forward(request, response);

	}
	
	private void validacao(String name) throws Exception{
			String [] nomeExt = name.split("\\.");
			int tamanho = nomeExt.length;
			if(tamanho > 2){
				throw new Exception("Arquivo nomeado com pontos, por favor, altere o nome e tente novamente");	
			}
	}

}
